﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Waker.Common;
using System.Diagnostics;
using DevExpress.Skins;
using System.Reflection;
using System.IO;
using Waker.Entitys;

namespace Waker
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                //Application.Run(new Temp.FormNVRTest());
                //Application.Run(new Cards.FormCardSetting());
                //return;
                Process instance = RunningInstance();
                if (instance == null)
                {
                    //DevExpress.UserSkins.BonusSkins.Register();
                    //DevExpress.UserSkins.OfficeSkins.Register();


                    Session._SkinName = new INIHelper(Consts.IniConfigPath).ReadValue("Skin", "SkinName");
                    if (string.IsNullOrEmpty(Session._SkinName))
                    {
                        Session._SkinName = DevExpress.Skins.SkinManager.DefaultSkinName;
                    }
                    DevExpress.LookAndFeel.UserLookAndFeel.Default.SkinName = Session._SkinName;
                    DevExpress.Utils.AppearanceObject.DefaultFont = new System.Drawing.Font("宋体", DevExpress.Utils.AppearanceObject.DefaultFont.Size);
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    // //处理未捕获的异常
                    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                    // //处理UI线程异常
                    Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                    // //处理非UI线程异常
                    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                    /* 处理界面UI风格 */
                    if (Environment.OSVersion.Version.Major <= 5 && Win32.IsThemeActive() == 0)
                    {
                        /* 如果是Windows XP或者Winows2003 并且没有使用主题（经典风格），
                         * 就使用DevExpress内置的窗口标题栏效果,否则就使用操作系统自带的标题栏效果
                         * 因为Vista和Windows7自身的的窗口标题栏效果比DevExpress的更好。
                         */
                        SkinManager.EnableFormSkins();
                    }
                    //FormSplash splashForm = new FormSplash(); /* 装载主窗口时显示一个启动画面。*/
                    //splashForm.Show();
                    //FormMain mainForm = new FormMain();
                    ////mainForm.splashForm = splashForm;
                    //CreateDesktopShortCut();/* 在桌面创建快捷图标 */
                    //Application.Run(mainForm);


                    //    显示Splash窗体
                    Splash.Show();

                    DoStartup();

                    // 关闭Splash窗体
                    Splash.Close();
                    //Application.Run(new FormMain());
                }
                else
                {
                    HandleRunningInstance(instance);
                }
            }
            catch (Exception ex)
            {
                //string str = "";
                //string strDateInfo = "出现应用程序未处理的异常：" + DateTime.Now.ToString() + "\r\n";

                //if (ex != null)
                //{
                //    str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n",
                //    ex.GetType().Name, ex.Message, ex.StackTrace);
                //}
                //else
                //{
                //    str = string.Format("应用程序线程错误:{0}", ex);
                //}

                //MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //writeLog(str);
                new Loger().LogException(ex);
                Application.DoEvents();
                UI.ShowError(ex.Message);
            }
        }
        static void DoStartup()
        {
            //    做需要的事情
            FormMain f = new FormMain();
            if (string.IsNullOrEmpty(Session._CurrUserCode))
                return;
            Application.Run(f);
        }

        /// <summary> 
        /// 获取正在运行的实例，没有运行的实例返回null; 
        /// </summary> 
        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }
            return null;
        }

        /// <summary> 
        /// 显示已运行的程序。 
        /// </summary> 
        public static void HandleRunningInstance(Process instance)
        {
            Win32.ShowWindowAsync(instance.MainWindowHandle, Win32.SW_SHOWMAXIMIZED); //显示，可以注释掉 
            Win32.SetForegroundWindow(instance.MainWindowHandle);            //放到前端 
        }

        /// <summary>
        /// 快捷方式
        /// </summary>
        private static void CreateDesktopShortCut()
        {
            string path = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu);
            path += @"\程序\Waker";
            if (Directory.Exists(path))
            {
                string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                desktop += "\\";
                foreach (string file in Directory.GetFiles(path))
                {
                    FileInfo fi = new FileInfo(file);
                    if (!File.Exists(desktop + fi.Name))
                    {
                        fi.CopyTo(desktop + fi.Name);
                    }
                }
            }
        }
        #region 捕捉全局异常代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {

            //string str = "";
            //string strDateInfo = "出现应用程序未处理的异常：" + DateTime.Now.ToString() + "\r\n";
            //Exception error = e.Exception as Exception;
            //if (error != null)
            //{
            //    str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n",
            //    error.GetType().Name, error.Message, error.StackTrace);
            //}
            //else
            //{
            //    str = string.Format("应用程序线程错误:{0}", e);
            //}

            //MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

            //writeLog(str);
            new Loger().LogException(e.Exception);
            Application.DoEvents();
            UI.ShowError(e.Exception.Message);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            //string str = "";
            Exception error = e.ExceptionObject as Exception;
            //string strDateInfo = "出现应用程序未处理的异常：" + DateTime.Now.ToString() + "\r\n";
            //if (error != null)
            //{
            //    str = string.Format(strDateInfo + "Application UnhandledException:{0};\n\r堆栈信息:{1}", error.Message, error.StackTrace);
            //}
            //else
            //{
            //    str = string.Format("Application UnhandledError:{0}", e);
            //}

            //MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

            //writeLog(str);
            new Loger().LogException(error);
            Application.DoEvents();
            UI.ShowError(error.Message);
        }

        ///// <summary>
        ///// 写文件
        ///// </summary>
        ///// <param name="str"></param>
        //static void writeLog(string str)
        //{
        // string ErrPath = AppDomain.CurrentDomain.BaseDirectory;

        // if (!Directory.Exists(ErrPath))
        // {
        // Directory.CreateDirectory(ErrPath);
        // }
        // using (StreamWriter sw = new StreamWriter( @"D:\ErrLog.txt", true))
        // {
        // sw.WriteLine(str);
        // sw.WriteLine("---------------------------------------------------------");
        // sw.Close();
        // }
        //}
        #endregion
    }
}
